// store.js
import { createStore } from 'vuex';

export default createStore({
    state: {
        historyRecord: [],
        messages: []
    },
    mutations: {


        addHistoryRecord(state, record) {
            state.historyRecord.unshift(record);
        },

        updateHistoryRecord(state, updatedRecord) {
            const index = state.historyRecord.findIndex(record => record.historyRecordId === updatedRecord.historyRecordId);
            if (index !== -1) {
                state.historyRecord[index] = updatedRecord;
            }
        },
        // 删除指定的 historyRecord（通过 ID）
        deleteHistoryRecord(state, historyRecordId) {
            state.historyRecord = state.historyRecord.filter(record => record.historyRecordId !== historyRecordId);
        },
        // 设置所有 historyRecord（用于初始化或重置）
        setAllHistoryRecords(state, records) {
            state.historyRecord = records;
        },

        addMessage(state, message) {
            state.messages.push(message);
        },
        // 删除指定 historyRecordId 的消息
        deleteMessage(state, historyRecordId) {
            state.messages = state.messages.filter(msg => msg.historyRecordId !== historyRecordId);
        }


    },
    actions: {

        addHistoryRecord({ commit }, record) {
            commit('addHistoryRecord', record);
        },

        updateHistoryRecord({ commit }, updatedRecord) {
            commit('updateHistoryRecord', updatedRecord);
        },
        deleteHistoryRecord({ commit }, historyRecordId) {
            commit('deleteHistoryRecord', historyRecordId);
        },

        setAllHistoryRecords({ commit }, records) {
            commit('setAllHistoryRecords', records);
        },

        addMessage({ commit }, message) {
            commit('addMessage', message);
        },
        // 异步删除消息
        deleteMessage({ commit }, historyRecordId) {
            commit('deleteMessage', historyRecordId);
        }
    },
    getters: {

        getHistoryRecords(state) {
            return state.historyRecord;
        },

        getHistoryRecordById: (state) => (id) => {
            return state.historyRecord.find(record => record.historyRecordId === id);
        },
        getMessagesByRecordId: (state) => (historyRecordId) => {
            return state.messages.find(msg => msg.historyRecordId === historyRecordId);
        },
    }
});
